package com.wxt.asmplugins;

import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.commons.AdviceAdapter;

/**
 * @author wuxiaotao on 2018/6/11.
 */
public class MyTestInjector extends ClassVisitor implements Opcodes {

    public MyTestInjector(ClassVisitor cv) {
        super(Opcodes.ASM5, cv);
    }

    @Override
    public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
        MethodVisitor mMV = cv.visitMethod(access, name, desc, signature, exceptions);
        if (name.equals("onClick") && desc.equals("(Landroid/view/View;)V")) {
            mMV.visitCode();
            mMV.visitVarInsn(ALOAD, 1); //读取参数 参数位置1，2，3，5 从1开始
            mMV.visitMethodInsn(INVOKESTATIC, "com/wxt/asmtest/Test", "onViewClick", "(Landroid/view/View;)V", false);
            Utils.log("Inject OnViewClickListener code in OnMyTestInjector");
            mMV.visitEnd();
        } else if(name.equals("onCreate")&& desc.equals("(Landroid/os/Bundle;)V")){
            mMV = new AdviceAdapter(Opcodes.ASM5, mMV, access, name, desc) {
                @Override
                protected void onMethodEnter() { //方法执行前加入字节码
                    super.onMethodEnter();
                    mv.visitCode();
                    mv.visitMethodInsn(INVOKESTATIC, "com/wxt/asmtest/Test", "onCreateBefore", "()V", false);
                    mv.visitEnd();
                }

                @Override
                protected void onMethodExit(int opcode) { //方法执行后
                    super.onMethodExit(opcode);
                    mv.visitCode();
                    mv.visitMethodInsn(INVOKESTATIC, "com/wxt/asmtest/Test", "onCreateAfter", "()V", false);
                    mv.visitEnd();
                }
            };
            return mMV;
        }
        return mMV;
    }

}
